const svgCaptcha = require('svg-captcha')
const redisConfig = require('../config/redisConfig.ts')
const aliyunMessage = require('../config/aliyunMessage.js')
const dayjs = require('dayjs')
const BackCode = require('../utils/BackCode.js')
const CodeEnum = require('../utils/CodeEnum.js')

const NotifyService ={
  captch:async(key,type)=>{
    let captcha = svgCaptcha.create({
      size: 4, // 验证码⻓度
      ignoreChars: '0o1i', // 验证码字符中排除 0o1i
      noise: 1, //⼲扰线
      background: '#aaa' // 背景颜⾊
    })
    redisConfig.set(type+':' + 'captcha' + key, captcha.text, 600)
    return captcha.data
  },
  sendCode:async(phone, captcha,type,key,randomCode)=>{
    // ////////方案1
    // 60s内不能重复获取
    // if (await redisConfig.exists(type+':' + 'over'+':' + phone)){
    //   return { code:-1, msg: '60s内不能重复获取'}
    // }


    // 方案2
    if (await redisConfig.exists(`${type}:code:` + phone)) {
        let dateRedis = dayjs(Number((await redisConfig.get(`${type}:code:` +
         phone)).split('_')[0]))
        if (dayjs(Date.now()).diff(dateRedis, 'second') <= 60) {
        // return { code: -1, msg: '60秒内不能重复获取' }
        return BackCode.buildResult(CodeEnum.CODE_LIMITED)
      }
    }


    // 是否有图形验证码
    console.log( await redisConfig.get(type+':' + 'captcha' + key), 'redis图形验证码')
    if (!await redisConfig.exists(type+':' + 'captcha' + key)){
      // return { code:-1, msg: '请发送图形验证码'}
      return BackCode.buildResult(CodeEnum.CODE_SEND)
    }
    // 判断图形验证码是否正确
    let captcharedis = await redisConfig.get(type+':' + 'captcha' + key)
    if(!captcha){
      return BackCode.buildError({msg:'缺少图形验证码'})
    }
    if(captcha.toLowerCase() !== captcharedis.toLowerCase() ){
      // return { code:-1, msg: '图形验证码错误'}
      console.log('图形验证码错误')
      return BackCode.buildError(CodeEnum.CODE_ERROR)
    }
    // 发送手机验证码
    let coderes = (await aliyunMessage(phone,randomCode)).data
    console.log(coderes, '++++++++++++=')
    
    // ////////方案1
    // 验证码存入redis
    // redisConfig.set(type+':' + 'code'+':' + phone, randomCode, 600)
    // 存60秒判断key值 60s后才能在发送短信
    // redisConfig.set(type+':' + 'over'+':' + phone, '1', 600)
    
    // 方案2
    // 验证码存入时拼接时间戳
    let randomcodeTime = `${Date.now()}_${randomCode}`
    redisConfig.set(type+':' + 'code'+':' + phone, randomcodeTime, 600)

    // 删除图形验证码
    redisConfig.del(type+':' + 'captcha' + key)
    if(coderes.code == '0'){
      // return { code:0, msg: '发送成功'}
      return BackCode.buildSuccessAndMsg({msg: '发送成功'})
      
    } else{
      // return { code:-1, msg: '发送失败'}
      return BackCode.buildError({msg: '发送失败'})
    }
  },
}

module.exports = NotifyService